// admin/system/service/sys_dept_service.go
package service

import (
	"errors"
	repo "go-admin1/admin/system/dao"
	"go-admin1/admin/system/model"
)

// SysDeptService 部门服务接口
type SysDeptService interface {
	Create(dept *model.SysDept) error
	GetByID(id int64) (*model.SysDept, error)
	Update(dept *model.SysDept) error
	Delete(id int64) error
	List(page, pageSize int) ([]*model.SysDept, int64, error)
	ListByParentID(parentID int64) ([]*model.SysDept, error)
}

type sysDeptService struct {
	deptDao repo.SysDeptDao
}

func (s sysDeptService) Create(dept *model.SysDept) error {
	return s.deptDao.Create(dept)
}

func (s sysDeptService) GetByID(id int64) (*model.SysDept, error) {
	dept, err := s.deptDao.GetByID(id)
	if err != nil {
		return nil, err
	}
	return dept, nil
}

func (s sysDeptService) Update(dept *model.SysDept) error {
	existingDept, err := s.deptDao.GetByID(dept.DeptID)
	if err != nil {
		return err
	}
	if existingDept == nil {
		return errors.New("部门不存在")
	}

	return s.deptDao.Update(dept)
}

func (s sysDeptService) Delete(id int64) error {
	existingDept, err := s.deptDao.GetByID(id)
	if err != nil {
		return err
	}
	if existingDept == nil {
		return errors.New("部门不存在")
	}

	return s.deptDao.Delete(id)
}

func (s sysDeptService) List(page, pageSize int) ([]*model.SysDept, int64, error) {
	depts, total, err := s.deptDao.List(page, pageSize)
	if err != nil {
		return nil, 0, err
	}
	return depts, total, err
}

func (s sysDeptService) ListByParentID(parentID int64) ([]*model.SysDept, error) {
	depts, err := s.deptDao.ListByParentID(parentID)
	if err != nil {
		return nil, err
	}
	return depts, nil
}

// NewSysDeptService 创建部门服务实例
func NewSysDeptService() SysDeptService {
	return &sysDeptService{
		deptDao: repo.NewSysDeptDao(),
	}
}
